package client.GUI;


import client.ClientTools.DateUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.Socket;
import java.util.concurrent.locks.ReentrantLock;

public class ChatClient extends Frame {

    private static final long serialVersionUID = 1L;

    String dockerUser = null;//用户名
    JTextArea jt = null;//显示的聊天内容
    JTextField inputField = null;//输入的聊天内容
    JTextArea jt4 = null;//用户

    //通信
    Socket s;

    {
        try {
            s = new Socket("127.0.0.1", 9000);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //聊天室界面
    public void launchFrame(String username) {

        this.dockerUser = username;//将里面的用户名传出

        //System.out.println(username);
        JFrame jf = new JFrame(username + "的聊天室");
        jf.setSize(800, 600);
        jf.setLocation(380, 150);
        jf.setVisible(true);
        //f.setUndecorated(true);//窗口边框不显示
        jf.setResizable(false);//固定窗口大小
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //布局
        jf.setLayout(new BorderLayout());

    /*
    左边
     */
        JPanel p1 = new JPanel();
        p1.setLayout(new BorderLayout());
        p1.setSize(400, 300);
        p1.setLocation(0, 0);
        p1.setVisible(true);


        //查看输入的聊天信息框
        jt = new JTextArea(20, 50);
        jt.setEditable(false);//设置他为不可编辑

        //滚动面板，将文本域作为显示组件
        JScrollPane js = new JScrollPane(jt);

        //文本框输入聊天信息
        inputField = new JTextField(25);
        JButton btn = new JButton("发送");

        JPanel p2 = new JPanel();
        p2.add(new JLabel("聊天内容"));
        p2.add(inputField);
        p2.add(btn);

        p1.add(new JLabel("聊天内容"), BorderLayout.NORTH);
        p1.add(js, BorderLayout.CENTER);
        p1.add(p2, BorderLayout.SOUTH);
    /*
    右边
     */
        JPanel p3 = new JPanel();
        p3.setSize(150, 50);
        p3.setLocation(10, 10);
        p3.setVisible(true);

        JTextArea jt3 = new JTextArea(14, 25);
        jt3.setEditable(false);//设置他为不可编辑
        //滚动面板，将文本域作为显示组件
        JScrollPane js3 = new JScrollPane(jt3);
        p3.add(new JLabel("群文件"), BorderLayout.PAGE_START);
        p3.add(js3, BorderLayout.PAGE_START);

        jt4 = new JTextArea(15, 25);
        jt4.setEditable(false);//设置他为不可编辑
        //jt4.setText(username+"（我）");

        //滚动面板，将文本域作为显示组件
        JScrollPane js1 = new JScrollPane(jt4);

        p3.add(new JLabel("当前在线人数"), BorderLayout.SOUTH);
        p3.add(js1, BorderLayout.SOUTH);


        //俩个面板
        //1左侧
        jf.add(p1, BorderLayout.LINE_START);

        //2右侧
        jf.add(p3, BorderLayout.CENTER);

        //后台处理

        //关闭按钮关闭程序
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        btn.addActionListener(new TFListener());//监听发送按钮

        //btn.doClick();

        new Thread(new RecvThread()).start();//多线程


    }
    ///////////////////
    /*
     *内部类
     */
    //////////////////

    //监听发送按钮内部类类
    class TFListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {

            DateUtil dateUtil = new DateUtil();
            String NowTime = dateUtil.getCurentDate();
            String strTitle = dockerUser + " " + NowTime;

            String strContent = inputField.getText().trim();//聊天信息，trim意思是去掉后面空格
            inputField.setText("");//清空输入窗口

            /*try {
                dos.writeUTF(strTitle);
                dos.writeUTF(strContent);
                dos.flush();//清空缓冲区

            } catch (IOException ioException) {
                ioException.printStackTrace();
            }*/
            PrintStream ps;
            try {
                ps = new PrintStream(s.getOutputStream());

                boolean flag = true;
                while (flag) {
                    ps.println();
                    flag = false;
                }

                ps.println(strTitle);
                ps.println(strContent);
            } catch (IOException ioException) {
                ioException.printStackTrace();
                System.out.println("消息发送失败!");
            }


        }
    }

    //线程类
    private class RecvThread implements Runnable {
        final ReentrantLock lock = new ReentrantLock();
        String rev;
        InputStream is;
        int flag = 0;//标志位

        @Override
        public void run() {
            {
                try {
                    is = s.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));

                    //System.out.println("进来了，但是没得输出");

                    while ((rev = br.readLine()) != null && rev != "\n") {
                        if (rev.equals("USER_START")) {
                            flag = 1;
                            jt4.setText("");
                        } else if (rev.equals("USER_END")) {
                            flag = 0;
                        } else if (flag == 1) {
                            jt4.append(rev + "\n");
                        } else {//群聊消息
                            lock.lock();//锁
                            try {
                                jt.setFont(new Font("宋体", Font.PLAIN, 15));
                                jt.setForeground(Color.blue);
                                jt.setText(jt.getText() + rev + '\n');
                                System.out.println(rev);
                            } finally {
                                lock.unlock();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
